package com.longkier.gx_library_springboot.Controller;

import com.longkier.gx_library_springboot.Service.UsersService;
import com.longkier.gx_library_springboot.entity.User;
import com.longkier.gx_library_springboot.exception.CustomException;
import com.longkier.gx_library_springboot.utils.RequestUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.*;
/**
 * 用户控制器，处理用户的请求。
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class UsersController {

    private final UsersService usersService;

    /**
     * 处理用户注册请求。
     *
     * @param user 用户实体
     * @return 注册结果
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        try {
            if (usersService.isUsernameTaken(user.getUsername())) {
                throw new CustomException(403, "用户名已存在");
            } else {
                usersService.registerUser(user);
                return RequestUtils.buildResponse("注册成功", 200);
            }
        } catch (Exception e) {
            throw new CustomException(500, "注册用户时发生异常");
        }
    }

    /**
     * 根据用户 ID 删除用户。
     *
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteUser(@PathVariable Long id) {
        try {
            boolean success = usersService.deleteUser(id);
            if (success) {
                return RequestUtils.buildResponse("删除成功",200);
            } else {
                throw new CustomException(404, "删除失败，用户不存在");
            }
        } catch (Exception e) {
            throw new CustomException(500, "删除用户时发生异常");
        }
    }

    /**
     * 批量删除用户
     *
     * @param params 请求体，包含 userIds
     * @return 删除结果
     */
    @DeleteMapping("/batch/delete")
    public Map<String, Object> batchDeleteUsers(@RequestBody Map<String, Object> params) {
        try {
            List<Long> userIds = RequestUtils.processIds(params.get("userIds"));
            boolean success = usersService.batchDeleteUsers(userIds);
            if (success) {
                return RequestUtils.buildResponse("删除成功",200);
            } else {
                throw new CustomException(500, "部分或全部用户删除失败");
            }
        } catch (IllegalArgumentException e) {
            throw new CustomException(400, e.getMessage());
        } catch (Exception e) {
            throw new CustomException(500, "删除用户时发生异常");
        }
    }

    /**
     * 分页查询所有用户。
     *
     * @param request 请求体，包含 page、size、status、username、cardName 和 cardNumber
     * @return 用户列表
     */
    @PostMapping("/all")
    public Map<String, Object> getUsers(@RequestBody Map<String, Object> request) {
        int page = (int) request.getOrDefault("page", 0);
        int size = (int) request.getOrDefault("size", 10);
        Integer status = (Integer) request.get("status");
        String username = (String) request.get("username");
        String cardName = (String) request.get("cardName");
        String cardNumber = RequestUtils.getStringFromRequest(request,"cardNumber");
        try {
            return RequestUtils.buildResponse(usersService.getUsersServices(page, size, status, username, cardName, cardNumber),200);
        } catch (Exception e) {
            throw new CustomException(500, "查询用户列表时发生异常");
        }
    }

    /**
     * 根据用户 ID、用户名或卡号查找用户详细信息。
     *
     * @param request 请求体，包含 userId、username 或 cardNumber
     * @return 用户详细信息或错误信息
     */
    @PostMapping("/getUserInfo")
    public Map<String, Object> getUserInfo(@RequestBody Map<String, Object> request) {
        try {
            Long userId = RequestUtils.getLongFromRequest(request);
            String username = (String) request.get("username");
            String cardNumber = RequestUtils.getStringFromRequest(request,"cardNumber");

            User user = usersService.getUserInfo(userId, username, cardNumber);
            if (user != null) {
                user.setPassword(null); // 隐藏密码
                return RequestUtils.buildResponse(user,200);
            } else {
                throw new CustomException(404, "用户不存在");
            }
        } catch (CustomException e) {
            throw e; // 直接抛出自定义异常
        } catch (Exception e) {
            throw new CustomException(500, "查询用户时发生异常");
        }
    }

    /**
     * 批量设置用户状态
     *
     * @param request 请求体，包含 userIds 和 status
     * @return 更新状态结果
     */
    @PutMapping("/batch/update/status")
    public Map<String, Object> batchUpdateStatus(@RequestBody Map<String, Object> request) {
        try {
            List<Long> userIds = RequestUtils.processIds(request.get("userIds"));
            Integer status = (Integer) request.get("status");

            boolean success = usersService.batchUpdateStatus(userIds, status);
            if (success) {
                return RequestUtils.buildResponse("更新状态成功",200);
            } else {
                throw new CustomException(500, "部分用户更新状态失败");
            }
        } catch (IllegalArgumentException e) {
            throw new CustomException(400, e.getMessage());
        } catch (Exception e) {
            throw new CustomException(500, "更新用户状态时发生异常");
        }
    }

    /**
     * 更新用户名。
     *
     * @param user 用户实体
     * @return 更新结果
     */
    @PutMapping("/update/name")
    public Map<String, Object> updateUser(@RequestBody User user) {
        try {
            boolean success = usersService.updateUser(user);
            if (success) {
                return RequestUtils.buildResponse("更新成功",200);
            } else {
                throw new CustomException(404, "更新失败，用户不存在");
            }
        } catch (Exception e) {
            throw new CustomException(500, "更新用户时发生异常");
        }
    }

    /**
     * 修改用户密码
     *
     * @param request 请求体，包含 userId 和 newPassword
     * @return 更新结果
     */
    @PutMapping("/update/password")
    public Map<String, Object> updatePasswordAndStatus(@RequestBody Map<String, Object> request) {
        try {
            Long userId = RequestUtils.getLongFromRequest(request);
            String newPassword = (String) request.get("newPassword");

            boolean success = usersService.updatePasswordAndStatus(userId, newPassword);
            if (success) {
                return RequestUtils.buildResponse("密码更新成功",200);
            } else {
                throw new CustomException(404, "用户不存在");
            }
        } catch (Exception e) {
            throw new CustomException(500, "更新用户密码和状态时发生异常");
        }
    }

    /**
     * 验证现有密码并修改用户密码
     *
     * @param request 请求体，包含 userId、currentPassword 和 newPassword
     * @return 更新结果
     */
    @PutMapping("/update/validate_password")
    public Map<String, Object> validateAndUpdatePassword(@RequestBody Map<String, Object> request) {
        try {
            Long userId = RequestUtils.getLongFromRequest(request);
            String currentPassword = (String) request.get("currentPassword");
            String newPassword = (String) request.get("newPassword");

            boolean success = usersService.validateAndUpdatePassword(userId, currentPassword, newPassword);
            if (success) {
                return RequestUtils.buildResponse("密码更新成功",200);
            } else {
                throw new CustomException(404, "密码验证失败或用户不存在");
            }
        } catch (Exception e) {
            throw new CustomException(500, "验证密码并更新时发生异常");
        }
    }


}